import yaml
from functools import reduce
  
def parse_yaml_file(file_path):  
    try: 
        with open(file_path, 'r') as file:
            data = yaml.safe_load(file)  
            return data
    except FileNotFoundError:  
        print(f"cannot find: {file_path}")  
        return None  
    except yaml.YAMLError as error:  
        print(f"failed to parse def file {file_path} with error: {error}")  
        return None  

def define_task(name,define_dict):
    enable = define_dict.get('enable',True)
    if not enable: return '//disabled task: {}'.format(name),'',''

    task_define='DEFINE_TASK({}); int {}(void*);'
    stack_define='word stack_{0}[{1}];'
    # creation='create_task({0}, stack_{0}, 1024*sizeof(word), &{1}, {2}, \"{3}\");'
    creation = 'struct AstralAttr attr_{0} = {{\n' \
               '    .base = &stack_{0},\n'\
               '    .stack_size = {1}*sizeof(word),\n'\
               '    .priority = {2},\n'\
               '    .name = \"{0}\",\n'\
               '    .method = {3}\n'\
               '}};\n'\
               ' create_task({0}, &attr_{0}, {4}, {5});\n'\
               ' distach_task({0});\n'

    stack = define_dict.get('stack','1024')
    entry = define_dict.get('entry')
    args = define_dict.get('args','NULL')
    prio = define_dict.get('priority','2')
    n1 = task_define.format(name, entry)
    n2 = stack_define.format(name, stack)
    n3 = creation.format(name, stack, prio, 0 ,entry, args)
    return n1,n2,n3

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='generate config file in cmake style')
    # Add optional args and there definitions
    parser.add_argument('--define', type=str, help='static define file')
    args = parser.parse_args()
    defs = parse_yaml_file(args.define)
    defs = list(map(lambda x: define_task(x,defs[x]),defs.keys()))
    static_create = 'void static_task_init(){{\n\t{}\n}}'
    sccontent = reduce(lambda x,y: x+'\n\t'+y, [item[2] for item in defs])
    print('#include "astralapi.h"')
    for item in defs: print(item[0])
    for item in defs: print(item[1])
    print(static_create.format(sccontent))